import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import Util from '../libs/util';
import Cookies from 'js-cookie';
import { routers } from './router';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
  mode: 'hash',
  routes: routers,
};
export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  const token = Cookies.get('token');
  // 权限控制
  authorityControl();

  function authorityControl() {
    // 未登录想进入系统内部
    if (noLogin()) {
      next({
        name: 'login',
      });
      iView.LoadingBar.finish();
    }
    // 已登录想返回login界面
    else if (hasLogin()) {
      next({
        name: 'uploader',
      });
      iView.LoadingBar.finish();
    } else {
      Util.title(to.meta.title);
      next();
    }
  }

  function noLogin() {
    const flag = !token && to.name !== 'login';
    return flag;
  }

  function hasLogin() {
    const flag = token && (to.name === 'login' || to.fullPath === '/');
    return flag;
  }
});

router.afterEach((to) => {
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
});
